package beans;

import net.HttpRequest;
import net.sf.json.JSONObject;

public enum TokenValue {
    TOKEN;
    private String tokenValue;

    TokenValue() {
       this.tokenValue = null;
    }


    public String getTokenValue(String userName, String passWord) {
        if(tokenValue==null){
            this.tokenValue = getNewTokenValue(userName,passWord);
        }else{
            //验证token有效性
            String result = HttpRequest.sendGet(beans.HttpConfig.checkToken,"token="+this.tokenValue);
            JSONObject resultJson = JSONObject.fromObject(result);
            if (!resultJson.getString("result").equals("success")) {
                this.tokenValue = getNewTokenValue(userName,passWord);
            }
        }
        return this.tokenValue;
    }

    /**
     * 新获取一个token
     * @param userName
     * @param passWord
     * @return
     */
    public String getNewTokenValue(String userName, String passWord) {
        JSONObject getNewJson = JSONObject.fromObject(HttpRequest.sendGet(beans.HttpConfig.tokenUrl,"username="+userName+"&password="+passWord));
        if(getNewJson.getString("result").equals("success")){
            JSONObject token = getNewJson.getJSONArray("data").getJSONObject(0);
            return token.getString("token");
        }else{
            return null;
        }
    }
}
